package com.jiajia.study.chapter01.nio;

import com.jiajia.study.utils.ByteBufferUtil;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.List;

/**
 * 网络编程 - 阻塞模式 - server 端
 * @author zjiajia
 * @date 2024/7/5 10:58
 */
public class TestServerV1 {
    public static void main(String[] args) throws IOException {
        ByteBuffer byteBuffer = ByteBuffer.allocate(32);
        // 创建 server 端
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        // 绑定端口
        serverSocketChannel.bind(new InetSocketAddress(8888));
        // 连接集合
        List<SocketChannel> channels = new ArrayList<>();

        while (true){
            /**
             * 默认这个方法是阻塞的，新的连接过来才会继续往下执行
             */
            SocketChannel socketChannel = serverSocketChannel.accept();
            channels.add(socketChannel);
            for(SocketChannel sc : channels){
                /**
                 * 默认 read 也是阻塞，只有 client 有数据写入，才会往下执行
                 */
                sc.read(byteBuffer);
                // 切换成写模式
                byteBuffer.flip();
                ByteBufferUtil.debugRead(byteBuffer);
                // 切换成写模式
                byteBuffer.clear();
            }
        }
    }
}
